import time

from django.core.cache import cache
from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin


# 中间件，统计功能
class HelloMiddle(MiddlewareMixin):
    def process_request(self, request):
        print(request.META.get("REMOTE_ADDR"))
        ip = request.META.get("REMOTE_ADDR")  # 记录log，统计信息
        print(request.path)
        # if request.path == "/Template/getphone/":
        #     if ip == "127.0.0.1":  # 提高权重，中奖概率
        #         return HttpResponse("恭喜你中奖了，抽中了一台Iphone")
        # if request.path == "/Template/getticket/":
        #     if ip.startswith("127.0.0.1"):
        #         return HttpResponse('优惠券还有5张')
        # if request.path == "/Template/search/":
        #     result = cache.get(ip)
        #     if result:
        #         return HttpResponse("你的访问过于频繁，请过10s在访问")
        #     cache.set(ip, ip, timeout=10)

        # black_list = []     # 黑名单用户
        # if ip in black_list:
        #     return HttpResponse("黑名单用户，一首凉凉总给自己")   # 判断黑名单，存在直接返回
        # requests = cache.get(ip, [])
        # while requests and time.time() - requests[-1] > 60:
        #     requests.pop()
        # requests.insert(0, time.time())
        # cache.set(ip, requests, timeout=60)
        #
        # if len(requests) > 30:
        #     black_list.append(ip)
        #     cache.set('balck', black_list, timeout=60 * 60 * 24)
        #     return HttpResponse("爬虫被关进小黑屋了")
        # if len(requests) > 10:
        #     return HttpResponse("请求过于频繁，请稍后再试")
